package com.inews.base.security.filter;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import com.inews.base.security.repository.SecurityDao;
import com.inews.business.entity.TblBaseResource;

@Component
public class MyInvocationSecurityMetadataSourceService implements
		FilterInvocationSecurityMetadataSource {

	private static final Logger logger = Logger
			.getLogger(MyInvocationSecurityMetadataSourceService.class);

	@Autowired
	private SecurityDao securityDao;

	private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

	public void loadResourceDefine() {
		if (resourceMap == null) {
			resourceMap = new LinkedHashMap<String, Collection<ConfigAttribute>>();
			List<TblBaseResource> resList = null;
			try {
				resList = securityDao.findTblBaseResourcePo();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			for (TblBaseResource resPo : resList) {
				String resUrl = "/" + resPo.getResourceUrl();
				ConfigAttribute configAttribute = new SecurityConfig(resPo.getResourceId());
				Collection<ConfigAttribute> configAttributes = null;
				if(resourceMap.containsKey(resUrl)){
					configAttributes = resourceMap.get(resUrl);
				}else{
					configAttributes = new ArrayList<ConfigAttribute>();
				}
				configAttributes.add(configAttribute);
				resourceMap.put(resUrl, configAttributes);
			}
		}
	}

	@Override
	public Collection<ConfigAttribute> getAttributes(Object paramObject)
			throws IllegalArgumentException {
		String url = ((FilterInvocation) paramObject).getRequestUrl();
		int firstQuestionMarkIndex = url.indexOf("?");
		if (firstQuestionMarkIndex != -1) {
			url = url.substring(0, firstQuestionMarkIndex);
		}
		logger.info("reqest url " + url);
		if (resourceMap == null) {
			loadResourceDefine();
		}
		return resourceMap.get(url);
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public boolean supports(Class<?> paramClass) {
		return true;
	}

}
